package com.gongj.hystrix.Command;


import com.gongj.commons.pojo.User;
import com.gongj.hystrix.service.HystrixService;
import com.gongj.hystrix.service.UserService;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @program: cloudlx
 * @description:关键的请求合并方法：
 * @author: gongj
 * @Description: TODO
 * @create: 2020-06-19 14:30
 **/
public class UserCollapserCommand extends HystrixCollapser<List<User>, User, String> {
    private UserService userService;
    private String id;

    public UserCollapserCommand(UserService userService, String id) {
        super(HystrixCollapser.Setter.withCollapserKey(
                HystrixCollapserKey.Factory.asKey("UserCollapseCommand"))
                .andCollapserPropertiesDefaults(
                        HystrixCollapserProperties.Setter().
                                withTimerDelayInMilliseconds(5000))
                .andScope(Scope.GLOBAL)
        );
        this.userService = userService;
        this.id = id;
    }

    /**
     * 请求参数
     *
     * @return
     */
    @Override
    public String getRequestArgument() {
        return id;
    }

    /**
     * 请求合并的方法
     *
     * @param collection
     * @return
     */
    @Override
    protected HystrixCommand<List<User>> createCommand(Collection<CollapsedRequest<User, String>> collection) {
        List<String> ids = new ArrayList<>(collection.size());
        for (CollapsedRequest<User, String> userIntegerCollapsedRequest : collection) {
            ids.add(userIntegerCollapsedRequest.getArgument());
        }
        return new UserBatchCommand(ids, userService);
    }

    /**
     * 请求结果分发
     *
     * @param users
     * @param collection
     */
    @Override
    protected void mapResponseToRequests(List<User> users, Collection<CollapsedRequest<User, String>> collection) {
        int count = 0;
        for (CollapsedRequest<User, String> request : collection) {
            request.setResponse(users.get(count++));
        }
    }
}
